import { ElMessage } from "element-plus";
import { hiprint, defaultElementTypeProvider } from "vue-plugin-hiprint";
import funcom from "@/utils/funComm";
const printSocketSroteV1 = defineStore("printSocket", {
  state: () => ({
    /**
     * 打印机socket实例
     */
    printSocketV1: null,
  }),
  actions: {
    /**
     * 初始化打印wocket
     */
    initPrintSocket() {

      try {
        this.printSocketV1 = new hiprint.init();
        hiprint.hiwebSocket.setHost(import.meta.env.VITE_APP_BASE_PRINT);
        funcom.success("打印机V1socket实例加载完成");
      } catch (err) {
        funcom.error("打印机V1socket实例加载失败");

        console.log(err);
      }
    },
    /**
     * 静默打印
     * @param {*} val
     * @param {*} config
     * 打印
     */
    print(val, config, ind) {
      return new Promise((resolve, reject) => {
        // 制作模版
        let hiprintTemplate = new hiprint.PrintTemplate({
          template: val.template,
        });
        console.log({ template: val.template, data: val.data });
        try {
          hiprintTemplate.print2(val.data, {
            printer: "",
            title: import.meta.env.VITE_PRINT_TITLE,
          });
        } catch (err) { }

        //  发送任务到打印机成功
        hiprintTemplate.on("printSuccess", (res) => {
          console.log(res);
          ElMessage["success"](res.msg + "---" + res.templateId);
          resolve(res);
        });
        // 发送任务到打印机失败
        hiprintTemplate.on("printError", (res) => {
          console.log(res);
          ElMessage["error"](res.msg + "---" + res.templateId);
          reject(res);
        });
      });
    },
    /**
     * 生成预览html
     * @param {*} val
     */
    viewPrint(val) {
      let hiprintTemplate = new hiprint.PrintTemplate({
        template: val.template,
      });
      // printData 如果是数组，那就是批量预览了
      let html = hiprintTemplate.getHtml(val.printData);
      // 渲染html
      console.log(
        `"$('#preview_content').length : "`,
        $("#preview_content").length
      );
      $("#preview_content").html(html);
    },
  },
});

export default printSocketSroteV1;
